﻿using BCCommon.Extensions;
using BCData.OA.GeneralDatabaseOperation;
using BCDto.OA.GeneralDatabaseOperation;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace BCService.OA.GeneralDatabasesOperation
{
    public class GeneralDatabasesOperationService: IGeneralDatabasesOperationService
    {
        private readonly IGeneralDatabasesOperationData generalDatabasesOperationData;

        public GeneralDatabasesOperationService(IGeneralDatabasesOperationData generalDatabasesOperationData)
        {
            this.generalDatabasesOperationData = generalDatabasesOperationData;
        }
        public IEnumerable<GeneralDatabaseOperationDatabaseNameDto> GetAllDatabaseName()
        {
            return this.generalDatabasesOperationData.GetAllDatabaseName().GetAwaiter().GetResult().As<IEnumerable<GeneralDatabaseOperationDatabaseNameDto>>();
        }

        public IEnumerable<GeneralDatabaseOperationTableNameDto> GetAllTableName(string databaseName)
        {
            CheckSafety(databaseName);
            return this.generalDatabasesOperationData.GetAllTableName(databaseName).GetAwaiter().GetResult().As<IEnumerable<GeneralDatabaseOperationTableNameDto>>();
        }

        public IEnumerable<GeneralDatabaseOperationColumnNameDto> GetAllColumnName(string databaseName, string tableName)
        {
            CheckSafety(databaseName);
            return this.generalDatabasesOperationData.GetAllColumnName(databaseName,tableName).GetAwaiter().GetResult().As<IEnumerable<GeneralDatabaseOperationColumnNameDto>>();
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="databaseName">数据库名称</param>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public IEnumerable<object> GetTableDataList(string databaseName, string tableName)
        {
            CheckSafety(databaseName);
            var data = this.generalDatabasesOperationData.GetTableDataList(databaseName,tableName).GetAwaiter().GetResult();
            return data;
        }

        public IEnumerable<Object> GetTableData(GeneralDatabasesOperationQueryDto queryDto)
        {
            CheckSafety(queryDto.DatabaseName);
            var data = this.generalDatabasesOperationData.GetTableData(queryDto.DatabaseName,queryDto.TableName, queryDto.ColumnName, queryDto.Wheres,queryDto.Symbol, queryDto.Parameters, queryDto.PageIndex, queryDto.PageSize).GetAwaiter().GetResult();
            return data;
        }

        private void CheckSafety(string databaseName)
        {
            string[] systemDatabases = new string[] { "information_schema", "cr_debug", "fxs", "performance_schema", "sys", "log", "mysql", "warning" };
            if (databaseName.In(systemDatabases))
            {
                throw new ArgumentException("你无权访问系统及数据库!!!");
            }
        }
    }
}
